{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings, ScopedTypeVariables, TypeSynonymInstances #-}
module Handler.Common where

import Foundation 

import Control.Applicative

import Settings.StaticFiles

import Control.Monad
import Control.Applicative ( (<$>) )

data Item = Item { route :: MSCRoute
                 , name  :: String
                 }                 
  
header :: Widget
header = [whamlet|
             <div .header .grid .panel>
                  ^{menuWidget items} 
         |]
  where
    items = [ Item MCHomeR  "ГЛАВНАЯ"
            , Item MCDemoR "ДЕМОНСТРАЦИЯ"
            ]

footer :: Widget
footer = [whamlet|
            <div .grid .panel>
               <div .credits .panel>
                   Cделано в #
                   <a href="http://www.inasan.ru">ИНАСАН
                   \ Copyright &copy; 2012
         |]

menuWidget :: [Item] -> Widget
menuWidget items = do
  Just r <- lift $ (liftA <$> getRouteToMaster) <*> getCurrentRoute
  toWidget [hamlet|
    <div .menu .panel>
       $forall item <- items
           $if isSelect item r
              <a .link .selected href=@{route item}>#{name item}
           $else
              <a .link href=@{route item}>#{name item}
  |] where isSelect item r = route item == r

--------------------------------------------------------------------------------

newDefaultLayout :: Widget -> Handler RepHtml
newDefaultLayout widget = do
        mmsg <- getMessage
        pc   <- widgetToPageContent $ do

                   addStylesheet $ StaticR css_default_css
                   addScript     $ StaticR js_jquery_js
                   addScript     $ StaticR js_plusstrap_js
                   addScript     $ StaticR js_application_js

                   $(widgetFile "default-layout-new")


        hamletToRepHtml $(hamletFile "default-layout-wrapper")


data Rubric = Rubric {title::String, url::MSCRoute, nodes::[Rubric]} deriving (Eq)

siteRubrics :: [Rubric]
siteRubrics = [ Rubric "ВКО-УФ" RootR
                  [ Rubric "О проетке" AboutR []
                  , Rubric "Основные цели" ObjectivesR []
                  , Rubric "Участники" ParticipantsR []
                  , Rubric "Контакты" ContactR []
                  ]

              , Rubric "Космический аппарат" SpacecraftR
                  [ Rubric "Платформа" PlatformR []
                  , Rubric "Телескоп" TelescopeR
                      [ Rubric "Оптическая система" OpticalSystemR []
                      , Rubric "Служебный комплекс" ServiceUnitR []
                      , Rubric "Система датчиков гида" FgsR []
                      ]
                  , Rubric "Научные приборы" InstrumentsR
                      [ Rubric "Блок камер поля" IssisR []
                      , Rubric "Спектрограф"     UvesR  []
                      , Rubric "Конус-УФ"        KonusR []
                      ]
                  , Rubric "Орбита" OrbitR []
                  , Rubric "Ракета-носитель" LaunchVehicleR [] 
                  ]

              , Rubric "Наземный сегмент" GroundSegmentR
                  [ Rubric "Комплекс управления" MissionOperationR []
                  , Rubric "Научный комплекс" ScienceOperationR []
                  , Rubric "Научный архив" DataArchiveR []
                  ]

              , Rubric "Новости" NewsR
                  [ Rubric "События" EventsR []
                  , Rubric "Конференции" ConferencesR []
                  , Rubric "Календарь" CalendarR []
                  , Rubric "Подписка на рассылку" SubscribeR []
                  ]
              , Rubric "Публикации" PublicationsR
                  [ Rubric "Изображения" ImagesR []
                  , Rubric "Видеосюжеты" VideosR []
                  ]
              ]

topRubric :: MSCRoute -> Maybe Rubric
topRubric r =  foldl mplus mzero $ map (\n -> (if (url n) == r then Just n else Nothing)  `mplus` (lookup n $ nodes n)) siteRubrics

 where

  lookup n (x:xs) | (r == url x) = Just n
                  | otherwise    = lookup n $ nodes x ++ xs

  lookup _     [] = Nothing

crumbs :: MSCRoute -> Maybe [Rubric]
crumbs r = r `lookup` (mkCrumbs siteRubrics [])
 
mkCrumbs []      _ = []
mkCrumbs (r:rs) cs = (url r,cs') : mkCrumbs (nodes r) cs' ++ mkCrumbs rs cs
  where
     cs' = cs ++ [r]


-- <img src=@{ StaticR img_logo_png }>
{--
   <div>
     <div .hidden-phone>
       <h1>
         <img src=@{ StaticR img_logo_bw_png }>
       <h2 .hidden-phone>
         Проект
     <div>
          <span .blue>Всемирная </span>
          <span .red>Космическая </span>
          <span .orange>Обсерватория </span>
          -
          <span .green> Ультрафиолет</span>
--}

mainHeader :: Widget
mainHeader = do 

 mr <- lift $ (liftA <$> getRouteToMaster) <*> getCurrentRoute

 let tr = case mr of
            Just r  -> case topRubric r of
                        Just tr -> title tr
                        _       -> ""
            _        -> ""

 [whamlet|

<div .container> 
    <h1>
      <img .hidden-phone src=@{ StaticR img_logo_bw_2_png }>
      <span .visible-phone>The World Space Observatory - Ultraviolet</span>
    
    <h2 .hidden-phone>
       #{ tr }
 
    <div .div-search .__ya-site-form .___ya-site-form_inited_no" onclick="return {'bg': 'transparent', 'target': '_self', 'language': 'ru', 'suggest': true, 'tld': 'ru', 'site_suggest': true, 'action': 'http://wsddo.inasan.ru', 'webopt': false, 'fontsize': 12, 'arrow': false, 'fg': '#000000', 'searchid': '2000831', 'logo': 'rb', 'websearch': false, 'type': 2}">
       <form .form-search action="http://yandex.ru/sitesearch" method="get" target="_self">
        <input type="hidden" name="searchid" value="2000831">
        <input type="hidden" name="l10n" value="ru">
        <input type="hidden" name="reqenc" value="">
        <input type="text" name="text" value="" .input .search-query>
        <button type="submit" .btn .btn-primary>
             <i .icon-search .icon-white>Поиск</i>
     <!--
     <style type="text/css">
       .ya-page_js_yes .ya-site-form_inited_no { display: none; }
     <script type="text/javascript">
       (function(w,d,c){var s=d.createElement('script'),h=d.getElementsByTagName('script')[0],e=d.documentElement;(' '+e.className+' ').indexOf(' ya-page_js_yes ')===-1&&(e.className+=' ya-page_js_yes');s.type='text/javascript';s.async=true;s.charset='utf-8';s.src=(d.location.protocol==='https:'?'https:':'http:')+'//site.yandex.net/v2.0/js/all.js';h.parentNode.insertBefore(s,h);(w[c]||(w[c]=[])).push(function(){Ya.Site.Form.init()})})(window,document,'yandex_site_callbacks');
     -->
     <!--
     <form .form-search action="http://yandex.com/sitesearch" method="get" target="_self">
           <input type="text" .input .search-query>
           <button type="submit" .btn .btn-primary>
             <i .icon-search .icon-white>Поиск</i>
     -->
   
|]

mainCrumb :: Widget
mainCrumb = do 

  mr <- lift $ (liftA <$> getRouteToMaster) <*> getCurrentRoute

  let mcrumbs = case mr of
                  Just r  -> crumbs r
                  Nothing -> Nothing

      Just cs = mcrumbs

  [whamlet|

    $if (/=) mcrumbs Nothing 
      $if not $ null cs
        <ol .container>
           ^{itemW cs}
  |]
  where
    itemW (x:[]) = [whamlet|
        <li>
          #{title x}
    |] 
    itemW (x:xs) = [whamlet|
        <li>
          <a href="@{url x}">#{title x}</a>
        ^{itemW xs}
    |]


mainMenu :: Widget
mainMenu  = do

 mr <- lift $ (liftA <$> getRouteToMaster) <*> getCurrentRoute

 let mitems = case mr of
               Just r  -> topRubric r
               Nothing -> Nothing

     Just r = mitems

 [whamlet|

  $if (/=) mitems Nothing

    <nav #main-menu role="navigation">

      <ul .nav .nav-stacked>

        ^{ itemW mr r }

 |]
  where


  isCurrent mr (Rubric _ r _) =
       case mr of
          Just cr -> r == cr
          Nothing -> False

  itemW mr r = [whamlet|

    <li>

       $if isCurrent mr r
            #{title r}
       $else
            <a href="@{url r}">#{title r}</a>

       $forall item <- nodes r
            <li>

              $if isCurrent mr item
                #{title item}
              $else
                <a href="@{url item}">#{title item}</a>

              $if not $ null (nodes item)
                <ul> 
                  $forall subitem <- nodes item
                     ^{ itemW mr subitem }

  |]

{--              
  <div id="main-menu">
    <ul .nav .nav-stacked>
      $forall item <- items
        <li>
          <a href="#">#{ fst item }</a>

          $if not $ null (snd item)
            <ul> 
              $forall subitem <- snd item
                <li><a href="#">#{ subitem }</a>

  items = [ ("Космичевский аппарат",    [])
          , ("Орбита",    [])
          , ("Ракета-носитель", [])
          , ("Платформа", [])
          , ("Телескоп",  [])
          , ("Научные приборы", [ "Блок камер поля"
                                , "Спектрограф"  
                                , "Конус-УФ"  
                                ])
          , ("Система датчиков гида", [])
           
          ] :: [(String, [String])]
--}

mainFooter :: Widget
mainFooter = [whamlet|

<div .container>

  <div #footer-local >
     ^{ localFooter }

  <div #footer-global>
    ^{ globalFooter }

 |]


globalFooter :: Widget
globalFooter = [whamlet|
  <ul>
    <li><a href="@{RootR}">Всё о ВКО-УФ</a>
    <li><a href="@{ContactR}">Контакты</a>
 |]


localFooter :: Widget
localFooter = do 

 mr <- lift $ (liftA <$> getRouteToMaster) <*> getCurrentRoute

 let isCurrent (Rubric _ r _) =
       case mr of
          Just cr -> r == cr
          Nothing -> False

 [whamlet|
<ul .footer-local>

    $forall item <- siteRubrics
      <li>

        $if isCurrent item
          #{title item}
        $else
          <a href=@{ url item }>#{ title item }</a>

        $with items <- nodes item
    
          $if not $ null items
            <ul> 
              $forall item <- items
                <li>
                   $if isCurrent item
                     #{title item}
                   $else
                     <a href=@{ url item }>#{ title item }</a>
 |]
 where

gallery :: [(MSCRoute, String)] -> Widget
gallery images = do

   addStylesheet $ StaticR css_gallery_css
   addScript     $ StaticR js_jquery_js

   addJulius     $(juliusFile  "gallery")

   [whamlet|

<div #carousel .row>

  <div #gallery .span7>
     
  <div #tabs .offset7 .span2>

    $forall image <- images
      <div>
         <img src=@{ url image } alt="#{ title image }">
|]

   where
       url   (r,_) = r
       title (_,t) = t

{--

  items = [("ВКО-УФ", [ "О проетке"
                      , "Основные цели"
                      , "Участники"
                      , "Контакты"
                      ])
{--
          , ("Участники",
                      [ "Научные организации"
                      , "Промышленость"
                      ])
--}

          , ("Космический аппарат",
                      [ "Орбита"
                      , "Ракета-носитель"
                      , "Платформа"
                      , "Телескоп"
                      , "Научные приборы"
                      , "Система датчиков гида"
                      ])

          , ("Наземный сегмент",
                      [ "Комплекс управления"
                      , "Научный комплекс"
                      , "Научный архив"
                      ])
{--
          , ("Наука", [ "Задачи"
                      , "Программа Наблюдений"
                      , "Научный Архив"
                      ])
--}
          , ("Новости", [ "События"
                        , "Конференции"
                        , "Календарь"
                        , "Подписка на рассылку"
                        ])
          , ("Публикации",[ "Изображения"
                          , "Видеосюжеты"
                          ])

          ] :: [(String, [String])]
--}

{--
  items = [ ("Кооперация",[ "Россия"
                          , "Испания"
                          , "Контакты"
                          ])

          , ("Проект",[ "Платформа"
                      , "Телескоп"
                      , "Научные приборы"
                      , "Наземный Сегмент"
                      , "Состояние Проекта"
                      ])
          , ("Наука", [ "Задачи"
                      , "Программа Наблюдений"
                      , "Научный Архив"
                      ])

          , ("Новости", [ "События"
                        , "Календарь"
                        ])
          , ("Публикации",[ "Изображения"
                          , "Видеосюжеты"
                          ])

          ] :: [(String, [String])]
--}
